package cn.itcast.n6_共享模型_无锁;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * Test01_转账问题
 * </p>
 *
 * @author flyduck
 * @since 2025/1/2
 */
@Slf4j(topic = "c.Test01_转账问题")
public class Test01_转账问题 {
    public static void main(String[] args) {
        Account account1 = new AccountUnsafe(10000);
        Account account2 = new AccountSynchronized(10000);
        Account account3 = new AccountCas(10000);
        Account.demo(account1);//290 cost: 45 ms
        Account.demo(account2);//0 cost: 50 ms
        Account.demo(account3);//0 cost: 40 ms
    }
}

class AccountCas implements Account{

    private AtomicInteger balance;

    public AccountCas(int balance) {
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return this.balance.get();
    }

    @Override
    public void withdraw(Integer amount) {
        while (true) {
            //获取余额最新值
            int prev = this.balance.get();
            //修改后的余额
            int next = prev - amount;
            //真正修改
            if (this.balance.compareAndSet(prev, next)) {
                break;
            }
        }
    }
}

class AccountSynchronized implements Account {

    private Integer balance;

    public AccountSynchronized(Integer balance) {
        this.balance = balance;
    }

    @Override
    public Integer getBalance() {
        synchronized (this) {
            return this.balance;
        }
    }

    @Override
    public void withdraw(Integer amount) {
        synchronized (this) {
            this.balance -= amount;
        }

    }
}

class AccountUnsafe implements Account {

    private Integer balance;

    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }

    @Override
    public Integer getBalance() {
        return this.balance;
    }

    @Override
    public void withdraw(Integer amount) {
        this.balance -= amount;
    }
}

interface Account {

    /**
     * 获取余额
     * @return
     */
    Integer getBalance();

    /**
     * 取款
     * @param amount
     */
    void withdraw(Integer amount);

    /**
     * 方法内会启动 1000 个线程，每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }
        long start = System.nanoTime();
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(account.getBalance()
                + " cost: " + (end-start)/1000_000 + " ms");
    }
}
